package leetcode_core.sort;

import org.junit.Test;

import java.util.Arrays;

public class BubbleSort {
    public static void bubbleSort(int[] arr){
        if(arr == null || arr.length <2){
            return;
        }
        //0-n-1
        //0-n-2
        //0-n-3
        //...
        //0-0
        //0-end
        for(int end = arr.length-1;end>=0;end--){
            //0~end
            //01 12 23 34 ... end-1:end
            for(int i = 0;i < end;i++){//我以开头为例解这个题
                if(arr[i] > arr[i+1]){
                    swap(arr,i,i+1);
                }
            }
            //for(int k = 1;k<= end;k++){//这是以结尾为例
                //if(arr[k-1] > arr[k]){
                    //swap(arr,k-1,k);
                //}
            //}
        }
    }


    private static void swap(int[] arr,int i,int j){
        int temp = arr[i];
        arr[i] = arr[j];
        arr[j] = temp;
    }

    @Test
    public void test(){
        int[] arr = {7, 1, 3, 5, 1, 6, 8, 1, 3, 5, 7, 5, 6};
        System.out.println(Arrays.toString(arr));
        bubbleSort(arr);
        System.out.println(Arrays.toString(arr));
    }
}
